package edu.gatech.oad.yuno;

import java.util.Calendar;

import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

/**
 * Activity for adding a new task OR editing an existing task
 * 
 * @author ryanfork
 *
 */

public class AddTodoActivity extends Activity implements View.OnClickListener {
	private Button buttonSave;
	private Button buttonCancel;
	private EditText editName;
	private EditText editDescription;
	private EditText editDate;
	private Spinner editCategory;
	private Spinner editLocation;
	private ImageButton newCategory;
	private ImageButton newLocation;
	private RatingBar editPriority;
	private CheckBox editRepeat;
	
	private ArrayAdapter<Category> catAdapter;
	ArrayAdapter<Location> locAdapter;
	
	private int mYear;
	private int mMonth;
	private int mDay;
	
	private Todo todo;

	static final int DATE_DIALOG_ID = 0;

	/**
	 * Date picker
	 */
	private DatePickerDialog.OnDateSetListener mDateSetListener =
			new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int month, int day) {
			mYear = year;
			mMonth = month;
			mDay = day;
			updateDisplay();
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_item);
	
		long todoId=this.getIntent().getLongExtra("ToDo", 0);
		adding();
		fillSpinners();
		if (todoId!=0){
			todo=new Todo(todoId);
			autofillStuff();
		}
	}
	
	/**
	 * Autofills the fields, given that we are editing, not creating
	 */
	private void autofillStuff(){
		
		Location loc=todo.getLocation();
		Category cat=todo.getCategory();
		Date dat=todo.getDueDate();
		if (dat!=null){
			String dateString=DateHelper.format(dat);
			editDate.setText(dateString);
		}
		
		String des=todo.getDescription();
		int pri=todo.getPriority();
		String name=todo.getName();
		boolean rep=todo.isRecurring();

		editDescription.setText(des);
		
		editName.setText(name);
		
		editPriority.setRating(pri);

		
		if (cat!=null){
			int catPosition=catAdapter.getPosition(cat);
			editCategory.setSelection(catPosition);
		}

		if (loc!=null){
			int locPosition=locAdapter.getPosition(loc);
			editLocation.setSelection(locPosition);
		}
		
	}
	
	
	/**
	 * Treats the activity as if we are creating a new task
	 */
	private void adding(){
		SharedPreferences prefs = getSharedPreferences("YUNoDos", MODE_PRIVATE);

		buttonSave = (Button) findViewById(R.id.buttonSave);
		//buttonCancel = (Button) findViewById(R.id.button2);

		editName = (EditText) findViewById(R.id.taskName);
		editDescription = (EditText) findViewById(R.id.taskDescription);
		editDate = (EditText) findViewById(R.id.editText1);
		editDate.setInputType(0);
		
		
		editCategory = (Spinner) findViewById(R.id.CatogoryPicker);
		
		
		editLocation = (Spinner) findViewById(R.id.locationPicker);
		
		newCategory = (ImageButton) findViewById(R.id.newCategoryButton);
		newLocation = (ImageButton) findViewById(R.id.newLocationButton);
		editPriority = (RatingBar) findViewById(R.id.selectPriority);
		editRepeat = (CheckBox) findViewById(R.id.taskRepeat);

		editDate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});

		final Calendar cal = Calendar.getInstance();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);
		
		buttonSave.setOnClickListener(this);
		newCategory.setOnClickListener(this);
		newLocation.setOnClickListener(this);
	}
	
	public void onResume() {
		super.onResume();
		fillSpinners();
	}
	
	private void fillSpinners() {
		Category selectedCategory = (Category)editCategory.getSelectedItem();
		Location selectedLocation = (Location)editLocation.getSelectedItem();
		
		SharedPreferences prefs = getSharedPreferences("YUNoDos", MODE_PRIVATE);
		
		List<Category> categories = Category.findAllByUser(prefs.getLong("logged_in_user_id", 0));
		Category dummy = new Category();
		dummy.setName("(None)");
		categories.add(0, dummy);
		catAdapter = new ArrayAdapter<Category>(this,
				android.R.layout.simple_spinner_item, categories);
		catAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		editCategory.setAdapter(catAdapter);
		
		List<Location> locations = Location.findAllByUser(prefs.getLong("logged_in_user_id", 0));
		Location dummyLocation = new Location();
		dummyLocation.setName("(None)");
		locations.add(0, dummyLocation);
		locAdapter = new ArrayAdapter<Location>(this,
				android.R.layout.simple_spinner_item, locations);
		locAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		editLocation.setAdapter(locAdapter);
		
		if (selectedCategory != null && selectedCategory.getId() != 0) {
			editCategory.setSelection(catAdapter.getPosition(selectedCategory));
		}
		if (selectedLocation != null && selectedLocation.getId() != 0) {
			editLocation.setSelection(locAdapter.getPosition(selectedLocation));
		}
	}

	/**
	 * Click listener
	 */
	public void onClick(View v) {
		if (v == buttonSave) {
			SharedPreferences prefs = getSharedPreferences("YUNoDos", MODE_PRIVATE);
			Date date = null;
			if (!editDate.getText().toString().equals(""))
				date = new Date(Date.parse(editDate.getText().toString()));
			if (todo==null){
				todo = new Todo();
				todo.setUser(prefs.getLong("logged_in_user_id", 0));
			}
			todo.setName(editName.getText().toString());
			todo.setDescription(editDescription.getText().toString());
			todo.setPriority((int) editPriority.getRating());
			todo.setDueDate(date);
			todo.setCategory((Category)editCategory.getSelectedItem());
			todo.setLocation((Location)editLocation.getSelectedItem());
			todo.setRecurring(editRepeat.isChecked());
			try {
				todo.validate();
				todo.save();
				finish();
				Toast.makeText(getApplicationContext(),editName.getText().toString() + " saved",
					Toast.LENGTH_SHORT).show();
			} catch (ValidationException e) {
				Toast.makeText(this, e.getMessage(),
	    				Toast.LENGTH_SHORT).show();
			}
		} else if (v == buttonCancel) {
			finish();
		} else if (v == newCategory) {
    		Intent intent = new Intent(this, AddCategoryActivity.class);
    		startActivity(intent);
		} else if (v == newLocation) {
    		Intent intent = new Intent(this, AddLocationActivity.class);
    		startActivity(intent);
		}
	}

	/**
	 * Updates the date displayed in the date field
	 */
	public void updateDisplay() {
		editDate.setText(new StringBuilder().append(mMonth + 1).append("/")
				.append(mDay).append("/").append(mYear));
	}
	
	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
		}
			return null;
	}
}
